package com.glory.brepda.activity.material;

import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.glory.brepda.R;
import com.glory.brepda.adapter.PickingDataAdapter;
import com.glory.brepda.base.MyApp;
import com.glory.brepda.entity.PickingEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.MyUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.adapter.FreeUI_NormalPopListAdapter;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.OnClick;

public class MaterialRlfAppointmentSendActivity extends MaterialRlfAppointmentActivity {

    private LinearLayout llMain;
    private NestedScrollView nsScroll;

    private MLotAppointmentSendAdapter mLotAppointmentAdapter;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_material_rlf_appointment_send;
    }

    @Override
    protected void initView() {

        llMain = findViewById(R.id.llMain);
        nsScroll = findViewById(R.id.nsScroll);
        flWorkShop = findViewById(R.id.flWorkShop);
        tvWorkShop = findViewById(R.id.tvWorkShop);
        ivWorkShop = findViewById(R.id.ivWorkShop);

        RecyclerView rvMLotAppointment = findViewById(R.id.rvMLotAppointment);
        initRecyclerView(rvMLotAppointment, MaterialRlfAppointmentSendActivity.this);

        // 送料领料单列表适配器定义，以及点击事件定义
        mLotAppointmentAdapter = new MLotAppointmentSendAdapter(null);
        mLotAppointmentAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mLotAppointmentAdapter.isFirstOnly(true);
        rvMLotAppointment.setAdapter(mLotAppointmentAdapter);

        // 设定点击事件，点击之后携带信息跳转到 MaterialRlfOutActivity页面进行扫描发料
        mLotAppointmentAdapter.setOnItemClickListener((adapter, view, position) -> {
            PickingEntity item = mLotAppointmentAdapter.getItem(position);
            if (item == null) {
                showToast("领料单数据获取错误，请联系管理员", false);
                return;
            }
            String confirmMessage = "批次号：" + item.getLOTID()
                    + "\r\n物料规格：" + item.getMATERIALSPEC()
                    + "\r\n指定供应商：" + (StringUtils.isEmpty(item.getRESERVED5()) ? "无" : item.getRESERVED5())
                    + "\r\n设备位置号：" + item.getEQPLOCATION()
                    + "\r\n确定执行送料？";

            // 执行领料单送料
            showSubmitDialog(() -> sendRLFAppointment(item.getOBJECTRRN(), position),
                    confirmMessage);
        });
    }

    @Override
    protected void initData() {

    }

    /**
     * 客制化主标题显示，本次主要重写右边按钮，点击按钮可以显示和隐藏搜索框
     *
     * @return 新的主标题，及其按钮
     */
    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("框架送料");

        freeUI_titleView.setRightListener("隐藏/显示", v -> {
            if (nsScroll.getVisibility() == View.VISIBLE) {
                nsScroll.setVisibility(View.GONE);
                return;
            }
            nsScroll.setVisibility(View.VISIBLE);
        });

        return new FreeUI_AddViewEntity("header", llMain);
    }


    /**
     * 获取领料单数据
     */
    @Override
    protected void requestForMLotRlfAppointment() {

        // 检查是否有去填写设备所属区域
        if (MyUtils.checkTextIsEmptyInAnyTextView(false, tvWorkShop)) {
            showToast("信息填写未完成，请检查", false);
            return;
        }

        // 清空原有数据框的数据
        MyUtils.clearDataInAdapter(mLotAppointmentAdapter);

        FreeUI_EntityCallBack<BaseResponseBean<PickingEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<PickingEntity>>
                (new TypeToken<BaseResponseBean<PickingEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<PickingEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {

                    List<PickingEntity> appointmentList = response.body().getResponse().getBody().getPickingEntityList();
                    if (appointmentList != null && appointmentList.size() > 0) {
                        mLotAppointmentAdapter.addData(appointmentList);
                        return;
                    }
                    showConfirmDialog("暂无领料申请");
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<PickingEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PICKAPPOINTMENT");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "QUERY_APPOINTMENT_INFO");
        map.addProperty("MATERIALTYPE", "框架");
        map.addProperty("WORKSHOP", String.valueOf(tvWorkShop.getText()));
        map.addProperty("STATUS", "OUT");// 选择状态为发料状态的执行送料
        NetUtils.requestPostNet("IF.PICKAPPOINTMENT", "Common", MaterialRlfAppointmentSendActivity.this, map, callBack);
    }

    @OnClick({R.id.flWorkShop, R.id.tvReset, R.id.tvSearch})
    public void onViewClicked(View view) {
        // 点击设备所属车间下拉框
        if (view.getId() == R.id.flWorkShop) {
            if (workShopPop != null) {
                if (workShopPop.isShowing()) {
                    workShopPop.dismiss();
                }
            } else {
                // 设置车间选择下拉框为多选框，点击选项时将对应选项加到 文本框里面，并将该选择从数据列表里面去除
                workShopPopListAdapter = new FreeUI_NormalPopListAdapter(workShopList);
                workShopPop = getNormalPop(getApplicationContext(), flWorkShop.getWidth(), workShopPopListAdapter, ivWorkShop, (codeS, i) -> {
                    final String newString = StringUtils.isEmpty(tvWorkShop.getText()) ? codeS : codeS + "," + tvWorkShop.getText();
                    tvWorkShop.setText(newString);
                    // 添加成功之后，去除掉相关的选项，想重新选必须进行重置
                    workShopPopListAdapter.remove(i);
                });
            }
            FreeApi_PopUtils.setArrowShow(ivWorkShop);
            workShopPop.showAsDropDown(flWorkShop, 0, 0);

        } else if (view.getId() == R.id.tvSearch) { // 点击查询，查询领料单信息
            requestForMLotRlfAppointment();
        } else if (view.getId() == R.id.tvReset) { // 点击重置，将搜索条件清空
            // 清除文本框中的数据
            if (StringUtils.isNotEmpty(tvWorkShop.getText())) {
                // 将文本框内的内容重新添加回去，车间数据列表里面
                workShopPopListAdapter.addData(Arrays.asList(StringUtils.split(String.valueOf(tvWorkShop.getText()), ",")));
                tvWorkShop.setText(StringUtils.EMPTY);
            }
        }
    }

    /**
     * 发送请求，领料单送料，后台执行领料单状态更新
     * @param pickingEntityObjectRrn 领料单主键
     */
    private void sendRLFAppointment(Long pickingEntityObjectRrn, int pickingEntityIndex) {

        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    showToast("送料成功", true);
                }
                requestForMLotRlfAppointment();
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(), "PICKAPPOINTMENT");
                requestForMLotRlfAppointment();
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "APPOINTMENT_MLOT_SEND");
        map.addProperty("MATERIALTYPE", "RLF");
        // 领料单信息提交到后台
        final ArrayList<PickingEntity> pickingEntities = new ArrayList<>(1);
        PickingEntity pickingEntity = new PickingEntity();
        pickingEntity.setOBJECTRRN(pickingEntityObjectRrn);
        pickingEntities.add(pickingEntity);
        map.add("APPOINTMENTTOOLLIST", new JsonParser().parse(new Gson().toJson(pickingEntities)).getAsJsonArray());
        NetUtils.requestPostNet("IF.PICKAPPOINTMENT", "Common", MaterialRlfAppointmentSendActivity.this, map, callBack);

    }
}

// 框架领料单送料数据适配器
class MLotAppointmentSendAdapter extends PickingDataAdapter {
    // 送料按钮点击监听器【客制化点击事件，可以回调到主activity上】
    private OnItemClickListener onItemClickListener;

    public MLotAppointmentSendAdapter(@Nullable List<PickingEntity> data) {
        super(data);
    }

    @Override
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    @Override
    protected void convert(BaseViewHolder helper, PickingEntity item) {
        // 以下栏位取消不要
        helper.getView(R.id.tvLotId).setVisibility(View.GONE);
        helper.getView(R.id.tvStep).setVisibility(View.GONE);

        // 设置送料文本框文字颜色
        helper.setTextColor(R.id.tvQty, MyApp.app.getResources().getColor(R.color.black));

        // 规格
        helper.setText(R.id.tvType, item.getMATERIALSPEC());
        // 数量
        helper.setText(R.id.tvSpec, item.getMAINQTY());
        // 设备位置
        helper.setText(R.id.tvEqpId, item.getEQPLOCATION());
        // 供应商
        helper.setText(R.id.tvEqpLocation, item.getRESERVED5());
        // 确认执行送料
        helper.setText(R.id.tvQty,"送料");

        // 注册监听器监听送料点击事件，执行事件回调
        helper.getView(R.id.tvQty).setOnClickListener(view -> {
            if ( onItemClickListener != null) {
                onItemClickListener.onItemClick(this, view, helper.getAdapterPosition());
            }
        });
    }

}
